package feces.servlet;

import java.io.IOException;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import feces.model.StorehouseProduct;
import feces.model.StorehouseProduct_;
import feces.utility.Utility;

/**
 * 库房商品管理伺服器
 */
@WebServlet(name="storehouse_products", urlPatterns={"/api/storehouse_products", "/api/StorehouseProServlet"})
@NoArgsConstructor
public class StorehouseProductsServlet extends RESTfulServlet {

	private static final long serialVersionUID = -5212253820030127798L;
	
	/**
	 * 字典
	 * 
	 * @author Bromine0x23
	 */
	@NoArgsConstructor(access = AccessLevel.PROTECTED)
	public static class Dictionary extends RESTfulServlet.Dictionary {

		public static final String STOREHOUSE_ID = "storehouseId";
	}

	/**
	 * 响应get方法，获取库房商品
	 */
	@Override
	protected Response<List<StorehouseProduct>> responseRead(
		HttpServletRequest request,
		HttpServletResponse response
	) throws ServletException, IOException {
		CriteriaBuilder builder = getCriteriaBuilder();
		CriteriaQuery<StorehouseProduct> query = builder.createQuery(StorehouseProduct.class);
		Root<StorehouseProduct> root = query.from(StorehouseProduct.class);
		String parameter;
		parameter = request.getParameter(Dictionary.STOREHOUSE_ID);
		if (!Utility.isEmpty(parameter)) {
			Integer id = Utility.toInteger(parameter);
			if (id == null) {
				return invalid(null);
			}
			query.where(builder.equal(root.get(StorehouseProduct_.storehouseId), id));
		}
		return succeed(executeQuery(query));
	}
	
}
